1 #!/usr/bin/python3
2 # Simple TicTacToe game in Python - EAO
3 import random
4 import sys
5
6 board=[i for i in range(0,9)]
7 player, computer = '',''
8
9 # Corners, Center and Others, respectively
10 moves=((1,7,3,9),(5,),(2,4,6,8))
11 # Winner combinations
12 winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
13 # Table
14 tab=range(1,10)
15
16 def print_board():
17 x=1
18 for i in board:
19 end = ' | '
20 if x%3 == 0:
21 end = ' \n'
22 if i != 1: end+='---------\n';
23 char=' '
24 if i in ('X','O'): char=i;
25 x+=1
26 print(char,end=end)
27
28 def select_char():
29 chars=('X','O')
30 if random.randint(0,1) == 0:
31 return chars[::-1]
32 return chars
33
34 def can_move(brd, player, move):
35 if move in tab and brd[move-1] == move-1:
36 return True
37 return False
38
39 def can_win(brd, player, move):
40 places=[]
41 x=0
42 for i in brd:
43 if i == player: places.append(x);
44 x+=1
45 win=True
46 for tup in winners:
47 win=True
48 for ix in tup:
49 if brd[ix] != player:
50 win=False
51 break
52 if win == True:
53 break
54 return win
55
56 def make_move(brd, player, move, undo=False):
57 if can_move(brd, player, move):
58 brd[move-1] = player
59 win=can_win(brd, player, move)
60 if undo:
61 brd[move-1] = move-1
62 return (True, win)
63 return (False, False)
64
65 # AI goes here
66 def computer_move():
67 move=-1
68 # If I can win, others don't matter.
69 for i in range(1,10):
70 if make_move(board, computer, i, True)[1]:
71 move=i
72 break
73 if move == -1:
74 # If player can win, block him.
75 for i in range(1,10):
76 if make_move(board, player, i, True)[1]:
77 move=i
78 break
79 if move == -1:
80 # Otherwise, try to take one of desired places.
81 for tup in moves:
82 for mv in tup:
83 if move == -1 and can_move(board, computer, mv):
84 move=mv
85 break
86 return make_move(board, computer, move)
87
88 def space_exist():
89 return board.count('X') + board.count('O') != 9
90
91 player, computer = select_char()
92 print('Player is [%s] and computer is [%s]' % (player, computer))
93 result='%%% Deuce ! %%%'
94 while space_exist():
95 print_board()
96 print('# Make your move ! [1-9] : ', end='')
97 move = int(input())
98 moved, won = make_move(board, player, move)
99 if not moved:
100 print(' >> Invalid number ! Try again !')
101 continue
102 #
103 if won:
104 result='*** Congratulations ! You won ! ***'
105 break
106 elif computer_move()[1]:
107 result='=== You lose ! =='
108 break;
109
110 print_board()
111 print(result)